package com.lottery.im.module.result.ui.game;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.GameHistoryInfo;
import com.lottery.im.api.result.entity.ResultInfo;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.common.WeakReferenceHandler;
import com.lottery.im.constant.Constants;
import com.lottery.im.constant.RxBusCode;
import com.lottery.im.module.result.adapter.result.item.Horizontal11530Adapter;
import com.lottery.im.module.result.adapter.result.item.HorizontalLottery30Adapter;
import com.lottery.im.module.result.presenter.GameDetailPresenter;
import com.lottery.im.module.result.ui.good.GetListFragment;
import com.lottery.im.module.result.ui.statistics.BallStatisticsFragment;
import com.lottery.im.module.result.ui.statistics.DoubleStatisticsFragment;
import com.lottery.im.module.result.ui.statistics.LongStatisticsFragment;
import com.lottery.im.module.result.ui.statistics.WinStatisticsFragment;
import com.lottery.im.module.result.view.GameDetailView;
import com.lottery.im.util.TimerUtils;
import com.lottery.im.util.rxbus.RxBus;
import com.lottery.im.view.LotteryVideoView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class GameLotteryFragment extends BaseSwipeFragment<GameDetailPresenter>
    implements GameDetailView {
  private final static String GAME_TYPE_KEY = "GAME_TYPE_KEY";
  private final static String GAME_TYPE_NAME_KEY = "GAME_TYPE_NAME_KEY";

  public static GameLotteryFragment create(String gameType, String gameTypeName) {
    GameLotteryFragment fragment = new GameLotteryFragment();
    Bundle b = new Bundle();
    b.putString(GAME_TYPE_KEY, gameType);
    b.putString(GAME_TYPE_NAME_KEY, gameTypeName);
    fragment.setArguments(b);
    return fragment;
  }

  @SuppressLint("HandlerLeak")
  private class MyHandler extends WeakReferenceHandler<BaseSwipeFragment> {
    public MyHandler(BaseSwipeFragment reference) {
      super(reference);
    }

    protected void handleMessage(BaseSwipeFragment reference, Message msg) {
      switch (msg.what) {
        case 0:
          if (null == mActivity || mActivity.isFinishing()) {
            return;
          }
          if (!"1".equals(isResult)) {
            presenter.queryAllGameTypeResult();
            RxBus.get().send(RxBusCode.REFRESH_CODE);
          }
          break;
      }
    }
  }

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.tv_master_plan) TextView mTvMasterPlan;
  @BindView(R.id.tv_game_sueId) TextView mTvSueId;
  @BindView(R.id.tv_game_lh) TextView mTvLh;
  @BindView(R.id.tv_he_zhi) TextView mTvHeZhi;
  @BindView(R.id.tv_game_time) TextView mTvTime;
  @BindView(R.id.progressBar) ProgressBar mProgressBar;
  @BindView(R.id.horizontal_list) RecyclerView mHRecyclerView;
  @BindView(R.id.tabLayout) CommonTabLayout mTabLayout;
  @BindView(R.id.lottery_video_view) LotteryVideoView mLotteryVideoView;

  private String[] mTabNames = { "开奖号码", "双面统计", "长龙统计", "号码分布" };
  private MyCountDownTimer mCountDownTimer;
  private String mGameType;
  private String mGameTypeName;
  private MyHandler mHandler;
  private Timer timer;
  private String isResult;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_game_lottery;
  }

  @Override protected void initPresenter() {
    presenter = new GameDetailPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    if (getArguments() == null) {
      popBackStack();
      return;
    } else {
      RxBus.get().register(this);
      mGameType = getArguments().getString(GAME_TYPE_KEY);
      mGameTypeName = getArguments().getString(GAME_TYPE_NAME_KEY);
      mTvTitle.setText(mGameTypeName);
      LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
      linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
      mHRecyclerView.setLayoutManager(linearLayoutManager);
      presenter.queryAllGameTypeResult();
      initTabs();
      mHandler = new MyHandler(this);
      timer = new Timer();
      timer.schedule(new TimerTask() {
        @Override
        public void run() {
          if (mHandler != null) {
            Message message = mHandler.obtainMessage(0);
            mHandler.handleMessage(message);
          }
        }
      }, 0, 5000);
      if (Constants.sd115Arr.contains(mGameType)) {
        mTvMasterPlan.setVisibility(View.GONE);
      } else {
        mTvMasterPlan.setVisibility(View.VISIBLE);
      }
    }
  }

  @OnClick({ R.id.iv_back, R.id.btn_anim, R.id.tv_master_plan })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.btn_anim:
        mLotteryVideoView.changeVisible();
        break;
      case R.id.tv_master_plan://高手计划
        startFragment(new GetListFragment(mGameType));
        break;
    }
  }

  /*
   *  初始化 tab
   * */
  private void initTabs() {
    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    for (int i = 0; i < mTabNames.length; i++) {
      final int position = i;
      tabEntities.add(new CustomTabEntity() {
        @Override public String getTabTitle() {
          return mTabNames[position];
        }

        @Override public int getTabSelectedIcon() {
          return 0;
        }

        @Override public int getTabUnselectedIcon() {
          return 0;
        }
      });
    }
    mTabLayout.setTabData(tabEntities);
    selectTab(0);
    mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
      @Override public void onTabSelect(int position) {
        selectTab(position);
      }

      @Override public void onTabReselect(int position) {
        selectTab(position);
      }
    });
  }

  public void selectTab(int position) {
    for (int i = 0; i < mTabNames.length; i++) {
      if (i == position) {
        TextView tv = mTabLayout.getTitleView(i);
        tv.setHeight((int) getResources().getDimension(R.dimen.space6));
        tv.setWidth((int) getResources().getDimension(R.dimen.dimen75));
        tv.setGravity(Gravity.CENTER);
        tv.setBackgroundResource(R.drawable.bg_tab_item_result);
      } else {
        TextView tv = mTabLayout.getTitleView(i);
        tv.setHeight((int) getResources().getDimension(R.dimen.space6));
        tv.setWidth((int) getResources().getDimension(R.dimen.dimen75));
        tv.setGravity(Gravity.CENTER);
        tv.setBackgroundResource(0);
      }
    }
    switchFragment(position);
  }

  private void switchFragment(int i) {
    String tag = String.valueOf(i);
    FragmentManager mFragmentManager = getChildFragmentManager();
    Fragment fragment = mFragmentManager.findFragmentByTag(tag);
    FragmentTransaction ft = mFragmentManager.beginTransaction();
    if (fragment == null) {
      switch (i) {
        case 0:
          fragment = WinStatisticsFragment.create(mGameType);
          break;
        case 1:
          fragment = DoubleStatisticsFragment.create(mGameType);
          break;
        case 2:
          fragment = LongStatisticsFragment.create(mGameType);
          break;
        case 3:
          fragment = BallStatisticsFragment.create(mGameType);
          break;
      }
      ft.replace(R.id.container_lottery, fragment, tag);
    } else {
      ft.show(fragment);
    }
    ft.commit();
  }

  @Override public void queryHistorySuccess(List<GameHistoryInfo> list) {
  }

  @Override public void querySuccess(List<ResultInfo> list) {
    for (ResultInfo resultInfo : list) {
      if (mGameType.equals(resultInfo.getGameType())) {

        boolean isNew = false;
        String s1 = mTvSueId.getText().toString();
        String s2 = resultInfo.getIssueId();
        if (!TextUtils.isEmpty(s1) && !s1.equals(s2)) {
          isNew = true;
        }

        mTvSueId.setText(resultInfo.getIssueId());
        String resultStr = resultInfo.getResultStr();
        StringBuffer allResult = new StringBuffer();
        if (resultStr.length() > 0) {
          String[] str = resultStr.split(",");
          if (str.length >= 5) {
            int w = Integer.parseInt(str[0]);
            int q = Integer.parseInt(str[1]);
            int b = Integer.parseInt(str[2]);
            int s = Integer.parseInt(str[3]);
            int g = Integer.parseInt(str[4]);
            int sum = w + q + b + s + g;
            String lh;
            String dx;
            String ds;
            if (w > g) {
              lh = "龙";
            } else if (w < g) {
              lh = "虎";
            } else {
              lh = "和";
            }
            if (Constants.lotteryArr.contains(mGameType)) {
              mHRecyclerView.setAdapter(new HorizontalLottery30Adapter(Arrays.asList(str)));
              if (sum >= 23) {
                dx = "大";
              } else {
                dx = "小";
              }
            } else {
              mHRecyclerView.setAdapter(new Horizontal11530Adapter(Arrays.asList(str)));
              if (sum >= 34) {
                dx = "大";
              } else {
                dx = "小";
              }
            }
            if (sum % 2 == 0) {
              ds = "双";
            } else {
              ds = "单";
            }
            mTvLh.setText(lh);
            mTvHeZhi.setText(sum + "    " + dx + "    " + ds);
            allResult.append(sum + "    " + dx + "    " + ds + "    " + lh);
            mLotteryVideoView.setTermAndResult(resultInfo.getIssueId(), str, allResult.toString());
            if (isNew) {
              mLotteryVideoView.setOpening(str);
            }
          }
        }
        long closeTime = resultInfo.getGMTcloseTime();
        long openTime = resultInfo.getGMTopenTime();
        long curTime = resultInfo.getGMTcurTime();
        isResult = resultInfo.getIsResult();
        mProgressBar.setMax((int) (closeTime - openTime) / 1000);
        if (closeTime - curTime > 0 && "1".equals(isResult)) {
          if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
          }
          mCountDownTimer =
              new MyCountDownTimer(closeTime - openTime, closeTime - curTime,
                  Constants.COUNT_DOWN_INTERVAL);
          mCountDownTimer.start();
        } else {
          mProgressBar.setProgress((int) (closeTime - openTime) / 1000);
          mTvTime.setText(R.string.opening);
          mLotteryVideoView.setWaiting("待开奖️");
          if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
          }
        }
      }
    }
  }

  class MyCountDownTimer extends CountDownTimer {
    private long max;

    public MyCountDownTimer(long max, long millisInFuture, long countDownInterval) {
      //微调防止跳过
      super(millisInFuture + millisInFuture * 2 / countDownInterval, countDownInterval);
      this.max = max;
    }

    @Override
    public void onTick(long millisUntilFinished) {
      if (mTvTime == null) return;
      mTvTime.setText(TimerUtils.formatDuring2(millisUntilFinished));
      String str = TimerUtils.formatDuring2(millisUntilFinished);
      mLotteryVideoView.setWaiting(str.substring(str.length() - 5, str.length()));
      mProgressBar.setProgress((int) max / 1000 - (int) millisUntilFinished / 1000);
    }

    @Override
    public void onFinish() {
      cancel();
      mTvTime.setText(R.string.opening);
      mLotteryVideoView.setWaiting("待开奖️");
      isResult = "0";
    }
  }

  @Override public void onDestroy() {
    super.onDestroy();
    RxBus.get().unRegister(this);
    if (mCountDownTimer != null) {
      mCountDownTimer.cancel();
    }
    mHandler.removeCallbacksAndMessages(null);
    mHandler = null;
    mCountDownTimer = null;
    mLotteryVideoView.cancel();
  }
}
